<?php

namespace app\admin\service;

use app\admin\validate\WebsiteSliderValidate;
use support\spark\exception\ApiException;
use \support\spark\model\system\WebsiteSlider;

class SliderService
{
    /**
     * 获取轮播列表
     * @param $param
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function getList($param)
    {
        $limit = $param['limit'];
        $name = $param['name'];

        $where = [];
        if (!empty($name)) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }

        $websiteSliderModel = new WebsiteSlider();
        $list = $websiteSliderModel->getPaginateList($where, ['*'], ['sort' => 'desc']);
        return dataReturn(0, 'success', $list);
    }

    /**
     * 添加轮播图
     * @param $param
     * @return array
     */
    public function addSlider($param)
    {
        // 检验完整性
        $validate = new WebsiteSliderValidate();
        if (!$validate->check($param)) {
            throw  new  ApiException($validate->getError(), -1);
        }
        $websiteSliderModel = new WebsiteSlider();
        $has = $websiteSliderModel->checkUnique([
            'name' => $param['name']
        ]);
        if (!empty($has)) {
            throw  new  ApiException('轮播描述已经存在', -1);
        }
        $param['create_time'] = now();
        $param['update_time'] = now();
        $websiteSliderModel->insertOne($param);
        return dataReturn(0, '添加成功');
    }

    /**
     * 编辑轮播图
     * @param $param
     * @return array
     */
    public function editSlider($param)
    {
        // 检验完整性
        $validate = new WebsiteSliderValidate();
        if (!$validate->check($param)) {
            throw  new  ApiException($validate->getError(), -1);
        }
        $websiteSliderModel = new WebsiteSlider();

        $where[] = ['id', '<>', $param['id']];
        $where[] = ['name', '=', $param['name']];
        $has = $websiteSliderModel->checkUnique($where);

        if (!empty($has)) {
            throw  new  ApiException('轮播描述已经存在', -1);
        }
        $param['update_time'] = now();
        $websiteSliderModel->updateById($param, $param['id']);
        return dataReturn(0, '编辑成功');
    }
}